package com.oJudge.judge;

import cn.hutool.json.JSONUtil;
import com.oJudge.common.ErrorCode;
import com.oJudge.exception.BusinessException;
import com.oJudge.judge.codeSandbox.CodeSandBoxFactory;
import com.oJudge.judge.codeSandbox.CodeSandbox;
import com.oJudge.judge.codeSandbox.CodeSandboxProxy;
import com.oJudge.judge.codeSandbox.modal.ExecuteCodeRequest;
import com.oJudge.judge.codeSandbox.modal.ExecuteCodeResponse;
import com.oJudge.judge.codeSandbox.modal.JudgeInfo;
import com.oJudge.judge.strategy.JudgeContext;
import com.oJudge.model.dto.question.JudgeCase;
import com.oJudge.model.entity.Question;
import com.oJudge.model.entity.QuestionSubmit;
import com.oJudge.model.enums.QuestionSubmiStatusEnum;
import com.oJudge.service.QuestionService;
import com.oJudge.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private JudgeManager judgeManager;

    @Value("${codesandbox.type}")
    private String type;

    /**
     * 判题
     *
     * @param questionSubmitId
     * @return
     */
    @Override
    public QuestionSubmit doJudge(Long questionSubmitId) {
        //获取题目提交信息
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交信息不存在");
        }
        //获取题目
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        //如果题目不为等待状态,则抛出错误
        if (!questionSubmit.getStatus().equals(QuestionSubmiStatusEnum.WAITING.getValue())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目正在判题中");
        }
        // 更新题目的提交信息
        QuestionSubmit questionSubmitUpdate = QuestionSubmit.builder()
                .id(questionSubmit.getId())
                .status(QuestionSubmiStatusEnum.RUNNING.getValue())
                .build();
        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目更新状态异常");
        }

        // 调用代码沙箱
        CodeSandbox codeSandbox = CodeSandBoxFactory.newInstance(type);
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest codeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        //调用代码沙箱执行代码
        ExecuteCodeResponse executeResponse = codeSandbox.executeCode(codeRequest);
        // 3.根据沙箱的执行结果,设置题目的判题状态和信息
        JudgeContext judgeContext = JudgeContext.builder()
                .inputList(inputList)
                .outputList(executeResponse.getOutputList())
                .judgeCaseList(judgeCaseList)
                .question(question)
                .questionSubmit(questionSubmit)
                .judgeInfo(executeResponse.getJudgeInfo())
                .build();
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        //修改数据库中的判题结果
        questionSubmitUpdate = QuestionSubmit.builder()
                .id(questionSubmit.getId())
                .status(QuestionSubmiStatusEnum.SUCCEED.getValue())
                .judgeInfo(JSONUtil.toJsonStr(judgeInfo))
                .build();
        update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目更新状态异常");
        }

        return questionSubmitService.getById(questionSubmitUpdate.getId());
    }
}
